package com.example.service;

import com.example.jparepository.secondary.entity.User;
import com.example.jparepository.secondary.repository.UserRepository;
import com.example.security.CustomAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collections;

@Service
public class CustomUserDetailsService implements UserDetailsService {

    private final UserRepository userRepository;

    public CustomUserDetailsService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 从数据库中加载用户
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new UsernameNotFoundException("User not found: " + username));

        // 将用户数据转换为 Spring Security 的 UserDetails 对象，并附加 uid
        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(),
                Collections.singletonList(new SimpleGrantedAuthority(user.getRole()))
        );
    }

    public CustomAuthenticationToken authenticateUser(String username, String password) throws UsernameNotFoundException {
        return authenticateUser(username);
    }

    public CustomAuthenticationToken authenticateUser(String username) {
        // 从数据库中加载用户
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new UsernameNotFoundException("User not found: " + username));

        // 这里可以假设密码校验已经由 Spring Security 完成，或者你也可以手动验证密码
        return new CustomAuthenticationToken(
                user.getUsername(),
                user.getPassword(),
                user.getId().toString(),  // 将 uid 放入 CustomAuthenticationToken 中
                Collections.singletonList(new SimpleGrantedAuthority(user.getRole()))
        );
    }
}
